/*
 * FstreamC.cpp
 *
 *  Created on: May 21, 2012
 *      Author: marchi
 */

#include "FstreamC.h"
void FstreamC::seekg(off_t n,string x){
	try{
		FILE * fp=gmx_fio_getfp(fin);
		if(x.find("beg") != string::npos)
			fseeko(fp,n,SEEK_SET);
		else if(x.find("end") != string::npos)
			fseeko(fp,n,SEEK_END);
		else if(x.find("cur") != string::npos)
			fseeko(fp,n,SEEK_CUR);
		else
			throw string("Seek direction unknown ");
	}
	catch(const string & s){
		cout << s << endl;
		exit(-1);
	}
}
void FstreamC::gFrameNumber(){
	FILE * fp=gmx_fio_getfp(fin);
	try{
		if(framesize){
			off_t pos0=0;
			fseeko(fp,pos0,SEEK_END);
			off_t pos1=ftello(fp);
			framenumber=static_cast<int> (pos1/framesize);
		} else throw string(" framesize must be initialized before computing the number of frames ");
	}
	catch(const string & s){
		cout << s << endl;
		exit(-1);
	}
}

void FstreamC::nextFrame(){
	nframe+=dStep;
}

void FstreamC::gFrameSize(){
	FILE * fp=gmx_fio_getfp(fin);
	gmx_fio_rewind(fin);
	rvec   *x;
	matrix box;
	int    natos,step0;
	real   prec,time0;
	gmx_bool   bOK;
	try{
		if(!read_first_xtc(fin,&natos,&step0,&time0,box,&x,&prec,&bOK))
			throw string("Cannot read first frame!");
	}
	catch(const string & s){
		cout << s << endl;
		exit(-1);
	}
	framesize=ftello(fp);
	delete [] x;
}
void FstreamC::sStep(){
	rvec   *x;
	matrix box;
	int    natos,step0,step1;
	real   prec,time0,time1;
	gmx_bool   bOK;

	try{
		if(!read_first_xtc(fin,&natos,&step0,&time0,box,&x,&prec,&bOK))
			throw string("Cannot read first frame!");
		if(!read_next_xtc(fin,natos,&step1,&time1,box,x,&prec,&bOK))
			throw string("Cannot read next frame!");
	}
	catch(const string & s){
		cout << s << endl;
		exit(-1);
	}
	dStep=step1-step0;
	offStep=step0;
	nframe=step0;
	gmx_fio_rewind(fin);
	delete [] x;
};

ios::pos_type FstreamC::tellg(){
	FILE * fp=gmx_fio_getfp(fin);
	return ftello(fp);
}


FstreamC::~FstreamC() {
	// TODO Auto-generated destructor stub
}

